# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, render, redirect

from web import models
from web.models import Web, WebForm, User


def archive(request):
    # post = Web(title='mocktitle', body='mockbody', timestamp=datetime.now())
    # return render_to_response('archive.html', {'post': post})

    # posts = Web.objects.all()
    posts = Web.objects.all ().order_by ('-timestamp')[:5]
    # return render_to_response('archive.html', {'web_list': posts})    #前面的html中要接受一个post参数的
    return render (request, 'archive.html', {'web_list': posts})


'''
#version one:
def create_context(request):
    if request.method == 'POST':
        Web(
            title=request.POST.get('title'),
            body=request.POST.get('body'),
            timestamp=datetime.now(),
        ).save()
    return HttpResponseRedirect('/test/')
'''


def create_context(request):
    if request.method == 'POST':
        form = WebForm (request.POST)
        if form.is_valid ():
            post = form.save (commit=False)  # 因为没有时间戳，所以先不提交，只是保存
            post.timestamp = datetime.now ()  # 添加了后再提交
            post.save ()
    return HttpResponseRedirect ('/test/')


def index(request):
    pass
    return render (request, 'login/index.html')


def login(request):
    if request.method == "POST":
        user_account = request.POST.get ('user_account')
        password = request.POST.get ('password')
        if user_account and password:  # 确保用户名和密码都不为空
            user_account = user_account.strip ()
            # 用户名字符合法性验证
            # 密码长度验证
            # 更多的其它验证.....
            try:
                user = User.objects.get (name=user_account)
                if user.password == password:
                    return redirect ('/index/')
                else:
                    message = "密码不正确！"
            except:
                message = "用户名不存在！"
            return render (request, 'login/login.html', {"message": message})
    return render (request, 'login/login.html')


def register(request):
    pass
    return render (request, 'login/register.html')


def logout(request):
    pass
    return redirect ('/index/')
